import React, { useState } from 'react';
interface Props {
  height?: number;
  width?: number;
  itemHeight?: number;
  list?: any[];
  children?: any;
}

const VariableSizeList: React.FC<Props> = (props) => {
  const { height, width, itemHeight, list, children: Child } = props;
  const containerStyle = {
    height,
    width,
    position: 'relative' as any,
    overflow: 'auto',
    border: '1px solid #000',
  };
  const [offsetTop, setOffsetTop] = useState(0);
  const contentStyle = {
    height: list.length * itemHeight,
  };
  function throttle(callback) {
    let requestId;
    return (...args) => {
      if (requestId) {
        return;
      }
      requestId = requestAnimationFrame(() => {
        callback.apply(this, args);
        requestId = null;
      });
    };
  }
  const scrollHandle = throttle((e: any) => {
    setOffsetTop(e.target.scrollTop);
  });

  const renderList = () => {
    const startIndex = Math.floor(offsetTop / itemHeight);
    const numVisible = Math.ceil(height / itemHeight);
    const finialStartIndex = Math.max(0, startIndex - 2);
    const endIndex = Math.min(startIndex + numVisible + 2, list.length);
    const raws = [];
    for (let i = finialStartIndex; i < endIndex; i++) {
      const itemStyle = {
        position: 'absolute',
        height: itemHeight,
        width: '100%',
        top: i * itemHeight, // 这里需要根据实际情况进行调整
      };
      raws.push(<Child key={i} data={i} style={itemStyle} />);
    }
    return raws;
  };
  return (
    <div style={containerStyle} onScroll={scrollHandle}>
      <div style={contentStyle}>{renderList()}</div>
    </div>
  );
};
export default VariableSizeList;
